<template>
	<div>
		<tencent-map ref="tencentMapForBuildingAreaMap" hasSearch zeroShowProp zeroShowExceptPointTypeSwitchProp
			:hasInfoAdd="mapShowAdd" :hasInfoEdit="mapShowEdit" :hasInfoDel="mapShowDel"
			:hasChoosedExport="mapShowExport" hasDateRange hasChoose :dateRange.sync="dateRange" @info-add="showAdd"
			@info-edit="showEdit" @info-del="showDel" @export-building="exportMP"></tencent-map>
		<el-dialog :close-on-click-modal="false" :title="(cuForm.id?'编辑':'新增')+'项目'" center :visible.sync="dialogCU"
			width="90%" @close="dialogCUClose('cuForm')">
			<el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" size="mini"
				label-width="130px" center>
				<el-divider content-position="left">基本信息</el-divider>
				<el-row :gutter="10">
					<el-col :span="16">
						<el-form-item label="照片">
							<upload-image :curImageProp="cuForm.photo" :ltSizeProp="2" hasDelBtn
								@upload-success="handleUploadImageSuccess" @upload-remove="handleUploadImageRemove">
								<span>不大于2MB</span>
							</upload-image>
						</el-form-item>
						<el-form-item label="分类" prop="type_id">
							<el-col :span="24">
								<el-radio-group v-model="cuForm.type_id" size="mini" @change="changeType">
									<el-radio-button v-for="(item,index) in types" :key="index" :label="item.id">
										{{ item.name }}
									</el-radio-button>
								</el-radio-group>
								<div class="text-xs"><span class="text-bold text-red">大牌</span>或<span
										class="text-bold text-red">大屏</span>，<span
										class="text-bold text-red">1</span>个项目只包含<span
										class="text-bold text-red">1</span>个点位
								</div>
							</el-col>
						</el-form-item>
						<el-form-item label="二级分类" prop="type_id_second"
							v-if="((types_second || new Map()).get(parseInt(cuForm.type_id)) || []).length > 0"
							key="type_id_second">
							<el-col :span="24">
								<el-radio-group v-model="cuForm.type_id_second" size="mini">
									<el-radio-button
										v-for="(item,index) in ((types_second || new Map()).get(parseInt(cuForm.type_id)) || [])"
										:key="index" :label="item.id">{{ item.name }}
									</el-radio-button>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="名称" prop="name">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.name" placeholder="请输入名称" />
							</el-col>
						</el-form-item>
						<!--            <el-form-item label="定位">-->
						<!--              <el-col :span="24">-->
						<!--                <div class="address-search flex justify-start align-center ">-->
						<!--                  <el-cascader slot="prepend" v-model="addNewSearchForm.pca" clearable filterable placeholder="请选择省市"-->
						<!--                               :options="pcAll" size="mini" class="address-cascader"-->
						<!--                  >-->
						<!--                  </el-cascader>-->
						<!--                  <el-button slot="append" icon="el-icon-search" style="margin-left:10px ;"-->
						<!--                             @click.native="searchAddress" size="mini" type="success" plain-->
						<!--                  >搜索位置-->
						<!--                  </el-button>-->
						<!--                  <span style="font-weight: bold; margin-left: 10px;">{{ cuForm.name }}</span>-->
						<!--                  <span style="color: red; margin-left: 10px;" v-if="cuForm.lat==null||cuForm.lng==null">(待定位)</span>-->
						<!--                  <span style="color: limegreen; margin-left: 10px;"-->
						<!--                        v-if="cuForm.lat!=null&&cuForm.lng!=null"-->
						<!--                  >(已定位)</span>-->
						<!--                </div>-->
						<!--              </el-col>-->
						<!--            </el-form-item>-->
						<el-form-item label="地址" prop="address">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.address" placeholder="请输入地址" />
							</el-col>
						</el-form-item>
						<el-form-item label="位置" prop="location_supply">
							<el-col :span="24">
								<el-input type="textarea" clearable :rows="1" placeholder="请输入位置补充说明"
									v-model="cuForm.location_supply" maxlength="200" show-word-limit>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="禁投行业" prop="forbid_industry_ids">
							<el-col :span="24">
								<el-select clearable filterable multiple v-model="cuForm.forbid_industry_ids"
									placeholder="选择禁止投放行业" style="width:100%">
									<el-option v-for="item in industryList" :key="item.id" :label="item.name"
										:value="item.id" :disabled="!item.status || !!item.deleted_at">
										<span style="float: left">{{ item.name }}</span>
										<span
											:style="{float:'right',color:(!!item.deleted_at?'#e54d42':(!item.status?'#8492a6':'')),fontSize:'12px'}">
											{{ !!item.deleted_at ? '已删除' : (!item.status ? '已禁用' : '') }}</span>
									</el-option>
								</el-select>
							</el-col>
						</el-form-item>
						<el-form-item label="有竞媒" prop="has_compete">
							<el-col :span="24">
								<el-radio-group v-model="cuForm.has_compete">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="地推活动" prop="can_ground_promote">
							<el-col :span="24">
								<el-radio-group v-model="cuForm.can_ground_promote">
									<el-radio :label="true">接受</el-radio>
									<el-radio :label="false">不接受</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="有偿商业宣传" prop="can_paid_ad">
							<el-col :span="24">
								<el-radio-group v-model="cuForm.can_paid_ad">
									<el-radio :label="true">接受</el-radio>
									<el-radio :label="false">不接受</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="车位数" prop="parking_count">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.parking_count" placeholder="请输入车位数" />
							</el-col>
						</el-form-item>
            <el-form-item label="电梯数" prop="elevator_count">
              <el-col :span="24">
                <el-input clearable v-model.trim="cuForm.elevator_count" placeholder="请输入电梯数" />
              </el-col>
            </el-form-item>
            <el-form-item label="电梯类型" prop="elevator_type">
              <el-col :span="24">
                <el-radio-group v-model="cuForm.elevator_type">
                  <el-radio :label="false">单梯</el-radio>
                  <el-radio :label="true">双梯</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
						<el-form-item label="物业费">
							<el-col :span="16">
								<el-input clearable v-model.trim="cuForm.management_fee" placeholder="请输入物业费" />
							</el-col>
							<el-col :span="8">
								<el-select filterable clearable v-model="cuForm.management_fee_unit_id"
									placeholder="请选择物业费单位" style="width:100%">
									<el-option v-for="item in management_fee_unit_ids" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
							</el-col>
						</el-form-item>
						<el-form-item label="受众" prop="audience_ids" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-select filterable clearable v-model="cuForm.audience_ids" multiple
									placeholder="请选择受众" style="width:100%">
									<el-option v-for="item in audiences" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
							</el-col>
						</el-form-item>
            <el-form-item label="指派工人" prop="worker_ids">
              <el-col :span="24">
                <el-select filterable clearable v-model="cuForm.worker_ids" multiple
                           placeholder="请选择指派工人" style="width:100%">
                  <el-option v-for="item in workers" :key="item.id" :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
						<el-form-item label="入住率" prop="occupancy_rate" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.occupancy_rate" type="number"
									placeholder="请输入入住率" max="100.00">
									<template slot="append">%</template>
								</el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="均价" prop="price" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.price" type="number" placeholder="请输入均价(元/平方)">
									<template slot="append">元/平方</template>
								</el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="最高楼层" prop="highest_floor" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.highest_floor" type="number"
									placeholder="请输入最高楼层">
									<template slot="append">层</template>
								</el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="入住年份" prop="check_in_at" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-date-picker v-model="cuForm.check_in_at" type="year" placeholder="请选择入住年份"
									value-format="yyyy-MM-dd" style="width:100%">
								</el-date-picker>
							</el-col>
						</el-form-item>
						<el-form-item label="居住规模" prop="scale" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.scale" type="number" placeholder="请输入入住规模">
									<template slot="append">人</template>
								</el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="单次固定售卖" prop="fix_sale_count_per_time" v-if="cuForm.type_id==78">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.fix_sale_count_per_time" type="number" placeholder="请输入单次固定售卖数">
									<template slot="append">个</template>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="16">
						<el-form-item label="覆盖地区" prop="cover_location">
							<el-col :span="24">
								<el-input type="textarea" clearable :rows="1" placeholder="请输入覆盖周边业态/小区/地址"
									v-model="cuForm.cover_location" maxlength="500" show-word-limit>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="覆盖人群" prop="cover_people_count">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuForm.cover_people_count" type="number"
									placeholder="请输入覆盖周边人口数量">
									<template slot="append">人</template>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="备注" prop="remark">
							<el-col :span="24">
								<el-input type="textarea" clearable :rows="2" placeholder="请输入备注"
									v-model="cuForm.remark" maxlength="500" show-word-limit>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-divider content-position="left">媒体点位数量</el-divider>
				<el-row :gutter="15">
					<el-col :span="12" v-if="(media_types || []).length > 0" v-for="(item,index) in (media_types || []).filter(m => {
					const that = this
					let list = that.type_map.get(cuForm.type_id) || []

					return list.indexOf(m.id)>-1
					})" :key="index">
						<el-form-item :label="item.name+'点位'" :key="item.id">
							<el-col :span="24">
								<el-input-number v-model="cuForm.media_types[''+item.id]" :min="0" :step="1"
									:disabled="!!pointCountInputDisabled" step-strictly controls-positio="right">
								</el-input-number>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click.native="dialogCU=false;">取 消</el-button>
				<el-button type="primary" v-if="cuForm.id!=null" @click.native="onSubmit(cuForm.id)">确 定</el-button>
				<el-button v-if="!cuForm.id&&!cuForm.lat" type="danger" disabled>请先定位</el-button>
				<el-button type="primary" v-if="cuForm.id==null&&(!!cuForm.lat&&!!cuForm.lng)"
					@click.native="onSubmit(cuForm.id)">提交</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import TencentMap from '@/components/TencentMap'
	import UploadImage from '@/components/UploadImage'
	import common from '@/utils/common.js'
	import {
		formatDate
	} from '@/utils/util.js'
	import {
		checkBtnRight
	} from '@/utils/auth.js'
	import {
		building_area_add,
		building_area_del,
		building_area_edit,
		get_media_types,
		ip_location,
		one,
		pc_list_all,
		search_address,
		get_media_type_relation,
		map_export_mp
	} from '@/api/building/building'
	import {
		list_all4th_by2ndcode,
		list_all3rd_bycode,
		list_all3rd_bycode_contrain_del_close
	} from '@/api/business/setting/dict'
  import { listWorker } from '@/api/workOrder/workOrder'

	export default {
		components: {
			TencentMap,
			UploadImage
		},
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy()
		// 	next()
		// },
		computed: {
			mapShowAdd() {
				return checkBtnRight('building_area_map_add')
			},
			mapShowEdit() {
				return checkBtnRight('building_area_map_edit')
			},
			mapShowDel() {
				return checkBtnRight('building_area_map_del')
			},
			mapShowExport() {
				return checkBtnRight('building_area_map_export')
			}
		},
		data() {
			var validateInput = (rule, value, callback) => {
				if (value.toString().indexOf('/') >= 0) {
					callback(new Error('不能含有特殊字符斜杠'))
				} else {
					callback()
				}
			}
			return {
				dateRange: [formatDate(new Date()) + ' 00:00:00', formatDate(new Date()) + ' 23:59:59'],
				// 项目编辑框loading
				dialogCULoading: false,
				// 增修弹框可见性
				dialogCU: false,
				// 项目信息表单
				cuForm: {
					id: null,
					photo: null,
					name: null,
					lat: null,
					lng: null,
					province: null,
					city: null,
					area: null,
					cdcode: null,
					address: null,
					price: null,
					type_id: 78,
					type_id_second: null,
					scale: null,
					fix_sale_count_per_time: null,
					occupancy_rate: null,
					audience_ids: [],
          worker_ids: [],
					parking_count: null,
          elevator_count: null,
          elevator_type: true,//默认双梯
					management_fee: null,
					management_fee_unit_id: null,
					forbid_industry_ids: [],
					highest_floor: null,
					check_in_at: null,
					has_compete: false,
					can_ground_promote: true,
					can_paid_ad: true,
					location_supply: null,
					cover_location: null,
					cover_people_count: null,
					remark: null,
					default_worker_id: null,
					points: [],
					media_types: {},
					mediaTypeRelation: []
				},
				// 点位类型
				media_types: [],
				media_types_map: new Map(),
				type_map: new Map(),
				// 社区分类
				types: [],
				typesMap: new Map(),
				// 社区二级分类
				types_second: new Map(),
				// 受众描述
				audiences: [],
        // 指派工人
        workers: [],
				management_fee_unit_ids: [],
				// 表单校验
				cuRules: {
					name: [{
						required: true,
						message: '请输入名称',
						trigger: 'blur'
					}]
				},
				// 所有省市
				pcAll: [],
				// 添加新项目 选地址表单
				addNewSearchForm: {
					pca: null,
					address: null
				},
				industryList: [],
				pointCountInputDisabled: false
			}
		},
		created() {
			this.getMediaTypes()
			this.getPCListAll()
			this.getIndustryList()
			this.getTypes()
			this.getMediaTypeRelation()
			this.getTypesSecond()
			this.getAudiences()
      this.getWorkers()
		},
		mounted() {

		},
		methods: {
			// 导出空闲点位
			exportMP(obj) {
				console.log('导出数据', obj)
				const loading = common.showLoading({
					text: '导出中'
				})
				map_export_mp(obj)
					.then(res => {
						if (res.data) {
							window.open(res.data, '_blank')
						}
						loading.close()
					}).catch(() => {
						loading.close()
					})
			},

			// 清除地图编辑器
			clearMapEditor(type) {
				this.$refs.tencentMapForBuildingAreaMap.clearMapEditor(type)
			},
			// 重新渲染地图项目
			refreshMapBuildingArea() {
				this.$refs.tencentMapForBuildingAreaMap.showBuildingAreas()
			},
			clearOneMarker(id) {
				this.$refs.tencentMapForBuildingAreaMap.clearOneMarker(id)
			},
			// 新增弹出框
			showAdd(data = {}) {
				console.log(data)
				this.clearOneMarker(data.id)
				if (JSON.stringify(data) != '{}') {
					this.cuForm.province = data.province
					this.cuForm.city = data.city
					this.cuForm.area = data.area
					this.cuForm.adcode = data.adcode
					this.cuForm.lat = data.lat
					this.cuForm.lng = data.lng
					this.cuForm.name = data.name
					this.cuForm.address = data.address
				}
				this.dialogCU = true
			},
			// 编辑弹出框
			showEdit(info) {
				this.dialogCULoading = true
				one({
					id: info.id
				}).then(res => {
					// 去除规格，合计点位数量
					let media_types = {};
					const uninstall_count = res.data.uninstall_media_types || {};
					const media_types_origin = res.data.media_types || {};
					const keys_mt = Object.keys(media_types_origin) || [];
					keys_mt.forEach(key => {
						const item = media_types_origin['' + key];
						const keys_spec = Object.keys(item) || [];
						keys_spec.forEach(inKey => {
							media_types['' + key] = parseInt(media_types['' + key] || 0) +
								parseInt(item['' + inKey] || 0);
						});
						if (!!uninstall_count['' + key]) media_types['' + key] = parseInt(media_types['' +
							key] || 0) + parseInt(uninstall_count['' + key] || 0);
					});
					this.cuForm = Object.assign({}, res.data, {
						media_types
					});
					this.dialogCULoading = false
				})
				this.dialogCU = true
			},
			// 删除确认
			async showDel(id) {
				const flag = await common.confirmDialog('删除项目，将同时注销项目点位，您确定吗？')
				if(!!flag){
					const loading = this.$loading({
						lock: true,
						text: '提交中',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					building_area_del({
						id
					}).then(res => {
						if (res.data) {
							this.$message.success('删除成功')
							this.clearOneMarker(id)
						}
						loading.close()
					}).catch(() => {
						loading.close()
					})
				}
			},
			// 获取社区分类
			getTypes() {
				const that = this
				return list_all3rd_bycode({
						code: 'xmxg-fl'
					})
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.types = data
							that.typesMap = new Map();
							(data || []).forEach(t => {
								that.typesMap.set(parseInt(t.id), t);
							})
						}
					})
			},
			// 获取社区分类
			getTypesSecond() {
				const that = this
				return list_all4th_by2ndcode({
						code: 'xmxg-fl'
					})
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							let map = new Map();
							(data || []).forEach(d => {
								let list = map.get(parseInt(d.pid)) || [];
								list.push(d);
								map.set(parseInt(d.pid), list);
							});
							that.types_second = map;
						}
					})
			},

			// 获取受众描述
			getAudiences() {
				const that = this
				return list_all3rd_bycode({
						code: 'xmxg-sz'
					})
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.audiences = data
						}
					})
			},
      //
      getWorkers() {
        listWorker().then(res => {
          this.workers = res.data
        })
      },
      // 获取点位类型
			getMediaTypes() {
				const that = this
				return get_media_types()
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.media_types = data || []
							that.media_types_map = new Map();
							(data || []).forEach(d => {
								that.media_types_map.set(parseInt(d.id), d)
								that.$set(that.cuForm.media_types, '' + d.id, 0)
							})
						}
					})
			},
			getMediaTypeRelation() {
				const that = this
				return get_media_type_relation()
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.mediaTypeRelation = data || []

							that.type_map = new Map();
							(data || []).forEach(d => {
								that.type_map.set(parseInt(d.building_area_type_id), d.media_type_ids)
							})
						}
					})
			},
			// 图片上传成功回调方法
			handleUploadImageSuccess(url) {
				this.cuForm.photo = url
			},
			handleUploadImageRemove() {
				this.cuForm.photo = ''
			},
			// 改变项目分类
			changeType() {
				const that = this
				if (that.cuForm.type_id == 84 || that.cuForm.type_id == 85) { // 大牌或大屏，默认一个项目对应一个点位
					if (that.cuForm.type_id == 84) that.$set(that.cuForm.media_types, '11', 1)
					// if (that.cuForm.type_id == 85) that.$set(that.cuForm.media_types, '12', 1)
					that.pointCountInputDisabled = true
				} else {
					that.pointCountInputDisabled = false
				}
			},
			// 获取所有省市
			getPCListAll() {
				const that = this
				return new Promise((resolve, reject) => {
					pc_list_all()
						.then(res => {
							const {
								code,
								data
							} = res
							if (code == 200) {
								if (data && data.length > 0) {
									that.pcAll = data
									resolve()
								}
							}
						})
				})
			},
			// 获取ip定位
			getIPLocation() {
				const that = this
				return new Promise((resolve, reject) => {
					ip_location()
						.then(res => {
							const {
								code,
								data: {
									status,
									result
								}
							} = res
							if (code == 200 && status == 0) {
								var adcode = result.ad_info.adcode
								const p = ('' + adcode).substring(0, 2)
								if ('' + p === '11' || '' + p === '12' || '' + p === '31' || '' + p === '50' ||
									'' + p === '81' || '' +
									p === '82') {
									// 直辖市和港澳时，只有一级
									that.addNewSearchForm.pca = [('' + adcode).substring(0, 2) + '0000']
								} else {
									that.addNewSearchForm.pca = [('' + adcode).substring(0, 2) + '0000', ('' +
											adcode).substring(0, 4) +
										'00'
									]
								}
							}
						})
				})
			},
			// 查询地址
			searchAddress() {
				const that = this
				that.addNewSearchForm.address = that.cuForm.name
				if (!that.addNewSearchForm.pca || that.addNewSearchForm.pca.length == 0) {
					common.message({
						message: '请选择省市',
						type: 'error'
					})
					return false
				}
				if (!that.addNewSearchForm.address) {
					common.message({
						message: '请输入名称',
						type: 'error'
					})
					return false
				}
				const loading = common.showLoading({
					text: '搜索中'
				})
				search_address({
						keyword: that.addNewSearchForm.address,
						boundary: that.addNewSearchForm.pca[that.addNewSearchForm.pca.length - 1]
					})
					.then(res => {
						const {
							code,
							data: {
								data
							}
						} = res
						if (code == 200) {
							loading.close()
							that.searchAddresses = data
							that.searchDialogVisible = true
						}
					})
					.catch(() => {
						loading.close()
					})
			},
			getIndustryList() {
				return list_all3rd_bycode_contrain_del_close({
						code: 'khxg-hy'
					})
					.then(res => {
						this.industryList = res.data
					})
			},
			getManagementFeeUnitIds() {
				return list_all3rd_bycode_contrain_del_close({
						code: 'xmxg-wyfdw'
					})
					.then(res => {
						this.management_fee_unit_ids = res.data
					})
			},
			dialogCUClose(formName) {
				const that = this
				this.refreshMapBuildingArea()
				switch (formName) {
					case 'cuForm':
						that.$refs['cuForm'].clearValidate()
						that.resetForm()
						break
				}
			},
			resetForm() {
				this.cuForm = {
					id: null,
					photo: null,
					name: null,
					lat: null,
					lng: null,
					province: null,
					city: null,
					area: null,
					cdcode: null,
					address: null,
					price: null,
					type_id: 78,
					type_id_second: null,
					scale: null,
					fix_sale_count_per_time: null,
					occupancy_rate: null,
					audience_ids: [],
					parking_count: null,
          elevator_count: null,
					management_fee: null,
					management_fee_unit_id: null,
					forbid_industry_ids: [],
					highest_floor: null,
					check_in_at: null,
					has_compete: false,
					can_ground_promote: true,
					can_paid_ad: true,
					location_supply: null,
					cover_location: null,
					cover_people_count: null,
					remark: null,
					default_worker_id: null,
					points: [],
					media_types: {}
				}
			},
			// 格式化Form
			formatFormData(obj) {
				if (obj.type_id != 78) {
					obj = Object.assign(obj, {
						price: null,
						scale: null,
						fix_sale_count_per_time: null,
						occupancy_rate: null,
						audience_ids: [],
						highest_floor: null,
						check_in_at: null
					})
				}
			},
			// 格式化媒体数据
			formatPointTypes(obj) {
				const that = this
				obj.points = []

				let keys = Object.keys(obj.media_types)
				if (keys && keys.length > 0) {
					for (let key of keys) {
						const count = parseInt(obj.media_types[key] || 0)
						let list = that.type_map.get(obj.type_id) || []
						if (count > 0 && list.indexOf(parseInt(key)) != -1) {
							obj.points.push({
								media_type_id: key,
								num: count
							})
						}
					}
				}
			},
			// 提交数据 增、改
			onSubmit(id) {
				// 表单校验
				this.$refs.cuForm.validate(valid => {
					// ~ 校验通过
					if (valid) {
						var obj = Object.assign({}, this.cuForm)

						delete obj.created_at
						delete obj.updated_at
						delete obj.deleted_at

						this.formatFormData(obj)

						this.formatPointTypes(obj)
						if (obj.management_fee != null && obj.management_fee != '') {
							if (obj.management_fee_unit_id == null || obj.management_fee_unit_id == '') {
								common.messageError('请选择物业费单位')
								return false
							}
						}
						if (obj.management_fee_unit_id != null && obj.management_fee_unit_id != '') {
							if (obj.management_fee == null || obj.management_fee == '') {
								common.messageError('请输入物业费')
								return false
							}
						}
						if ((obj.points || []).length == 0) {
							common.messageError('请输入点位数量')
							return false
						}

						// 显示loading
						this.dialogCULoading = true

						// ~~ 修改
						if (id) {
							this.onEdit(obj)
						} else {
							// ~~ 添加
							delete obj.id
							this.onAdd(obj)
						}
					} else {
						// ~ 不通过
						return false
					}
				})
			},
			// 添加
			onAdd(obj) {
				building_area_add(obj)
					.then(res => {
						const {
							code,
							message
						} = res
						if (code === 200) {
							common.message({
								message
							})
							this.dialogCU = false
							this.getList()
						}
						this.dialogCULoading = false

					})
					.catch(() => {
						this.dialogCULoading = false

					})
			},
			// 编辑
			onEdit(obj) {
				building_area_edit(obj)
					.then(res => {
						const {
							code,
							message
						} = res
						if (code === 200) {
							common.message({
								message
							})
							this.dialogCU = false
							this.getList()
						}
						this.dialogCULoading = false
					})
					.catch(() => {
						this.dialogCULoading = false
					})
			}
		}
	}
</script>

<style scoped lang="scss">
	.building-code-input {
		/deep/ .el-input__inner {
			padding-left: 5px !important;
			padding-right: 5px !important;
			text-align: center;
		}
	}

	.building-code-collapse.el-collapse {
		border-top: none;
	}
</style>
